package app 
{
	import app.view.MainView;

	import com.bumpslide.tween.FTween;
	import com.bumpslide.ui.Applet;
	import com.bumpslide.ui.Box;
	import com.bumpslide.ui.PixelIcon;

	import flash.display.BitmapData;
	import flash.events.Event;

	/**
	 * Application Root, the Document Class for 'main.fla' 
	 * 
	 * The root of your .FLA file should be nothing but a blank frame.
	 * Make this the document class for your FLA file.  It will initialize 
	 * the application framework (controller, model, service, stageProxy ) 
	 * and then attach the main view of your application.
	 * 
	 * This class should remain a reusable part of the app template, and
	 * should not be cluttered with app logic.
	 * 
	 * @see app.Controller
	 * @see app.view.MainView
	 * 
	 * @author David Knape
	 */
	public class AppRoot extends Applet {
		
		public var background:Box;
		public var mainView:MainView;
		public var controller:Controller;

		private const BACKGROUND_PIXELS:Array = [
			'  *',
			' * ',
			'*  '
		];
		override protected function addChildren():void {
			super.addChildren();
						
			debugEnabled = false;
			
			// make a background (here we are using some pixel art made with code)
			background = new Box();
			background.tileBitmap = new BitmapData(3,3, true, 0x000000);
			background.tileBitmap.draw( new PixelIcon( BACKGROUND_PIXELS, 0x222222) );
			addChild( background );
		}

		/**
		 * Where we initialize our controller
		 * 
		 * If there is a preloader, we will be added to the stage once loading is complete.
		 * If we are true _root, then this event will dispatch right away.
		 */
		override protected function onAddedToStage(e:Event):void {
			super.onAddedToStage(e);
			// init controller, and call initView when startup is complete
			controller = new Controller( this, initView );
		}

		/**
		 * Create the main view and configure stage proxy
		 */
		public function initView():void {						
			debug('initView()');
			
			mainView = new MainView();
			mainView.visible = false;
			FTween.fadeIn( mainView, 500, .5 );
			addChild( mainView );  
			
			stageProxy.updateDelay = 0; 
			stageProxy.setBounds( 500, 400, 1200, 1000);
			
			// size didn't change, so we need to force update
			updateNow();       
		}   
		
		/**
		 * This gets called on stage resize since this class extends Applet
		 */
		override protected function draw():void {
			if(!stage) return;
			
			debug('draw');
			
			// background should fill true stage dimensions and bleed over a bit 
			background.setSize( stage.stageWidth+200, stage.stageHeight+200);
								
			// size main view to stageProxy constraints and center if we're maxed out
			if(mainView) {
				mainView.x = Math.max( Math.round((stage.stageWidth-width)/2), 0);
				mainView.setSize( width, height );	
			}									
			super.draw();
		}
	}
}
